<template>
  <div class="publish-article" v-loading="isPublishing" element-loading-text="正在发布..." element-loading-background="rgba(255,255,255,0.6)">
    <div class="publish-container">
      <!-- 顶部操作栏 -->
      <header class="publish-header">
        <button class="back-btn" @click="handleBack">
          <svg viewBox="0 0 24 24" fill="none" xmlns="http://www.w3.org/2000/svg">
            <path d="M19 12H5M12 19l-7-7 7-7" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"/>
          </svg>
          返回
        </button>
        <h1 class="publish-title">发布文章</h1>
        <div class="header-actions">
          <button class="draft-btn" @click="handleSaveDraft">
            <svg viewBox="0 0 24 24" fill="none" xmlns="http://www.w3.org/2000/svg">
              <path d="M19 21H5a2 2 0 0 1-2-2V5a2 2 0 0 1 2-2h11l5 5v11a2 2 0 0 1-2 2z" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"/>
              <polyline points="17 21 17 13 7 13 7 21" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"/>
              <polyline points="7 3 7 8 15 8" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"/>
            </svg>
            存草稿
          </button>
          <button class="publish-btn" @click="handlePublish" :disabled="!canPublish">
            <svg viewBox="0 0 24 24" fill="none" xmlns="http://www.w3.org/2000/svg">
              <path d="M22 2L11 13M22 2l-7 20-4-9-9-4 20-7z" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"/>
            </svg>
            发布
          </button>
        </div>
      </header>

      <!-- 表单内容 -->
      <div class="publish-content">
        <div class="form-section">
          <!-- 标题输入 -->
          <div class="form-group">
            <label class="form-label">文章标题 <span class="required">*</span></label>
            <input
              v-model="article.title"
              type="text"
              placeholder="输入一个吸引人的标题..."
              class="title-input"
              maxlength="100"
            />
            <div class="input-tip">{{ article.title.length }}/100</div>
          </div>

          <!-- 内容输入 -->
          <div class="form-group">
            <label class="form-label">文章内容 <span class="required">*</span></label>
            <textarea
              v-model="article.content"
              placeholder="分享你的旅行故事、攻略、心得..."
              class="content-textarea"
              rows="20"
            ></textarea>
            <div class="input-tip">{{ article.content.length }} 字</div>
          </div>

          <!-- 图片上传 -->
          <div class="form-group">
            <label class="form-label">文章配图 <span class="optional">(可选，最多9张)</span></label>
            <div class="images-upload">
              <div class="images-grid">
                <div v-for="(image, index) in previewImages" :key="index" class="image-item">
                  <img :src="image" :alt="`图片 ${index + 1}`" />
                  <button class="remove-image-btn" @click="removeImage(index)">
                    <svg viewBox="0 0 24 24" fill="none" xmlns="http://www.w3.org/2000/svg">
                      <path d="M18 6L6 18M6 6l12 12" stroke="currentColor" stroke-width="2" stroke-linecap="round"/>
                    </svg>
                  </button>
                </div>
                <div v-if="previewImages.length < 9" class="upload-image-area" @click="selectImages">
                  <svg viewBox="0 0 24 24" fill="none" xmlns="http://www.w3.org/2000/svg">
                    <path d="M12 5v14M5 12h14" stroke="currentColor" stroke-width="2" stroke-linecap="round"/>
                  </svg>
                  <span>添加图片</span>
                </div>
              </div>
              <input ref="imagesInput" type="file" accept="image/*" multiple @change="handleImagesUpload" style="display: none" />
            </div>
          </div>

          <!-- 标签选择 -->
          <div class="form-group">
            <label class="form-label">文章标签 <span class="optional">(最多选择3个)</span></label>
            <div class="tags-selector">
              <button
                v-for="type in availableTags"
                :key="getTypeKey(type)"
                :class="['tag-option', { active: selectedTypeIds.includes(getTypeKey(type)) }]"
                @click="toggleTag(type)"
                :disabled="selectedTypeIds.length >= 3 && !selectedTypeIds.includes(getTypeKey(type))"
              >
                {{ getTypeName(type) }}
              </button>
            </div>
            <div v-if="article.tags.length > 0" class="selected-tags">
              <span class="selected-label">已选择:</span>
              <div class="selected-tags-list">
                <span v-for="tag in article.tags" :key="tag" class="selected-tag">
                  {{ tag }}
                  <button @click="removeTag(tag)" class="remove-tag-btn">×</button>
                </span>
              </div>
            </div>
          </div>
        </div>
      </div>
    </div>

    <!-- 发布确认弹窗（Element Plus） -->
    <el-dialog
      v-model="showPublishDialog"
      title="确认发布文章？"
      width="420px"
      :close-on-click-modal="!isPublishing"
      :close-on-press-escape="!isPublishing"
      :show-close="!isPublishing"
    >
      <div class="dialog-message">文章发布后将在社区展示，其他用户可以查看和评论。</div>
      <template #footer>
        <div class="dialog-actions">
          <el-button @click="showPublishDialog = false" :disabled="isPublishing">取消</el-button>
          <el-button type="primary" @click="confirmPublish" :loading="isPublishing">确认发布</el-button>
        </div>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, computed, onMounted, onBeforeUnmount } from 'vue'
import { useRouter } from 'vue-router'
import { fileApi, articleApi, typeApi } from '@/utils/api'
import { ElMessage } from 'element-plus'

const router = useRouter()

const userInfo = ref(null)
const isUploading = ref(false)
const isPublishing = ref(false)

onMounted(() => {
  const storedUserInfo = localStorage.getItem('userInfo')
  if (storedUserInfo) {
    try { userInfo.value = JSON.parse(storedUserInfo) } catch {}
  }
  loadTypes()
})

// 表单数据
const article = ref({
  title: '',
  content: '',
  images: [],
  tags: []
})

// 可选标签
const availableTags = ref([])
const selectedTypeIds = ref([])
const previewImages = ref([])
const selectedFiles = ref([])

// 引用
const imagesInput = ref(null)

// 弹窗状态
const showPublishDialog = ref(false)

// 计算属性：是否可以发布
const canPublish = computed(() => {
  return (
    article.value.title.trim() !== '' &&
    article.value.content.trim() !== '' &&
    selectedTypeIds.value.length > 0
  )
})

// 方法
function handleBack() {
  if (article.value.title || article.value.content) {
    if (confirm('返回将丢失未保存的内容，确认返回吗？')) {
      router.back()
    }
  } else {
    router.back()
  }
}

function handleSaveDraft() {
  if (!article.value.title && !article.value.content) {
    ElMessage.warning('标题和内容不能都为空')
    return
  }

  // TODO: 调用API保存草稿
  console.log('保存草稿:', article.value)
  ElMessage.success('草稿已保存')
}

function handlePublish() {
  if (!canPublish.value) {
    ElMessage.warning('请填写标题、内容并选择至少一个类型')
    return
  }
  showPublishDialog.value = true
}

async function confirmPublish() {
  try {
    // TODO: 调用API发布文章
    const uId = (userInfo.value && (userInfo.value.userId || userInfo.value.uId)) || 0
    if (!uId) {
      ElMessage.warning('请先登录再发布文章')
      return
    }

    isPublishing.value = true

    let uploadUrls = article.value.images || []
    if (selectedFiles.value && selectedFiles.value.length > 0) {
      try {
        const res = await fileApi.uploads(selectedFiles.value)
        let urls = []
        if (res && typeof res === 'object' && 'data' in res && res.data != null) {
          const d = res.data
          if (Array.isArray(d)) {
            urls = d
          } else if (typeof d === 'string') {
            urls = d.split(',').map(s => s.trim()).filter(Boolean)
          }
        } else if (Array.isArray(res)) {
          urls = res
        } else if (typeof res === 'string') {
          try {
            const parsed = JSON.parse(res)
            const d2 = parsed && parsed.data
            if (Array.isArray(d2)) urls = d2
            else if (typeof d2 === 'string') urls = d2.split(',').map(s => s.trim()).filter(Boolean)
            else urls = res.split(',').map(s => s.trim()).filter(Boolean)
          } catch {
            urls = res.split(',').map(s => s.trim()).filter(Boolean)
          }
        }
        uploadUrls = urls
      } catch (e) {
        ElMessage.error('图片上传失败，请重试')
        return
      }
    }
    article.value.images = uploadUrls

    const tIdsNormalized = (selectedTypeIds.value || []).map(k => {
      if (typeof k === 'number') return k
      if (typeof k === 'string') {
        const num = Number(k)
        if (Number.isFinite(num)) return num
        if (k.startsWith('name:')) {
          const name = k.slice(5)
          const found = (availableTags.value || []).find(t => getTypeName(t) === name)
          const id = found && (found.tId ?? found.id ?? found.typeId ?? found.typeID ?? found.tid ?? found.TId ?? found.TID)
          if (id !== undefined && id !== null && Number.isFinite(Number(id))) {
            return Number(id)
          }
        }
      }
      return NaN
    }).filter(n => Number.isFinite(n))

    if (!tIdsNormalized.length) {
      ElMessage.warning('所选标签缺少ID，请刷新后重试')
      return
    }

    const res = await articleApi.addEssay({
      uId,
      title: article.value.title,
      content: article.value.content,
      status: 'PUBLISHED',
      images: article.value.images,
      tIds: tIdsNormalized
    })

    if (res && typeof res === 'object' && 'code' in res) {
      if (res.code !== 0 && res.code !== 200) {
        throw new Error(res.message || '发布失败')
      }
    }

    ElMessage.success('文章发布成功！')
    showPublishDialog.value = false
    router.push('/community/articles')
  } catch (error) {
    console.error('发布失败:', error)
    ElMessage.error('发布失败，请重试')
  } finally {
    isPublishing.value = false
  }
}

// 文章配图
function selectImages() {
  imagesInput.value?.click()
}

function handleImagesUpload(event) {
  const files = Array.from(event.target.files || [])
  if (!files.length) return

  // 检查数量限制
  const remainingSlots = 9 - (selectedFiles.value.length || 0)
  const toAdd = files.slice(0, remainingSlots)
  if (toAdd.length === 0) return

  toAdd.forEach(f => {
    selectedFiles.value.push(f)
    try {
      const url = URL.createObjectURL(f)
      previewImages.value.push(url)
    } catch {}
  })

  // 清空input
  if (imagesInput.value) {
    imagesInput.value.value = ''
  }

  // 验证文件类型
  // 验证文件大小
  // 创建预览URL
  // 清空input
  // TODO: 上传到服务器
}

function removeImage(index) {
  const f = selectedFiles.value[index]
  if (f) {
    selectedFiles.value.splice(index, 1)
  }
  const url = previewImages.value[index]
  if (url) {
    try { URL.revokeObjectURL(url) } catch {}
    previewImages.value.splice(index, 1)
  }
}

// 标签
function getTypeKey(type) {
  if (typeof type === 'string') return `name:${type}`
  const id = type && (type.tId ?? type.id ?? type.typeId ?? type.typeID ?? type.tid ?? type.TId ?? type.TID)
  if (id !== undefined && id !== null) return String(id)
  const name = type && (type.tName ?? type.tname ?? type.name)
  return name ? `name:${name}` : ''
}

function getTypeName(type) {
  if (typeof type === 'string') return type
  return (type && (type.tName ?? type.tname ?? type.name)) || ''
}

function toggleTag(type) {
  const key = getTypeKey(type)
  const name = getTypeName(type)
  const idx = selectedTypeIds.value.indexOf(key)
  if (idx > -1) {
    selectedTypeIds.value.splice(idx, 1)
    const nidx = article.value.tags.indexOf(name)
    if (nidx > -1) article.value.tags.splice(nidx, 1)
  } else if (selectedTypeIds.value.length < 3) {
    selectedTypeIds.value.push(key)
    if (name && !article.value.tags.includes(name)) {
      article.value.tags.push(name)
    }
  }
}

function removeTag(tag) {
  const index = article.value.tags.indexOf(tag)
  if (index > -1) {
    article.value.tags.splice(index, 1)
  }
  const typeObj = (availableTags.value || []).find(t => getTypeName(t) === tag)
  if (typeObj) {
    const key = getTypeKey(typeObj)
    const i2 = selectedTypeIds.value.indexOf(key)
    if (i2 > -1) selectedTypeIds.value.splice(i2, 1)
  }
}

async function loadTypes() {
  try {
    const response = await typeApi.listType()
    let typeList = []
    if (Array.isArray(response)) {
      typeList = response
    } else if (response && typeof response === 'object' && response.data && Array.isArray(response.data)) {
      typeList = response.data
    }
    availableTags.value = typeList
  } catch (e) {
    void e
  }
}

onBeforeUnmount(() => {
  const urls = previewImages.value || []
  urls.forEach(u => { try { URL.revokeObjectURL(u) } catch {} })
})
</script>

<style scoped>
.publish-article {
  min-height: 100vh;
  background: #f9fafb;
  padding-top: 64px;
}

.publish-container {
  max-width: 900px;
  margin: 0 auto;
}

.publish-header {
  background: #ffffff;
  border-bottom: 1px solid #eef0f5;
  padding: 20px 24px;
  display: flex;
  align-items: center;
  justify-content: space-between;
  gap: 16px;
  position: sticky;
  top: 64px;
  z-index: 100;
}

.back-btn {
  display: flex;
  align-items: center;
  gap: 6px;
  padding: 8px 12px;
  background: #f9fafb;
  border: 1px solid #e5e7eb;
  border-radius: 8px;
  font-size: 14px;
  color: #6b7280;
  cursor: pointer;
  transition: all 0.2s ease;
}

.back-btn:hover {
  background: #f3f4f6;
  color: #4b5563;
}

.back-btn svg {
  width: 18px;
  height: 18px;
}

.publish-title {
  font-size: 20px;
  font-weight: 700;
  color: #2b2f36;
  margin: 0;
  flex: 1;
}

.header-actions {
  display: flex;
  gap: 12px;
}

.draft-btn {
  display: flex;
  align-items: center;
  gap: 6px;
  padding: 10px 16px;
  background: #f9fafb;
  border: 1px solid #e5e7eb;
  border-radius: 8px;
  font-size: 14px;
  font-weight: 500;
  color: #6b7280;
  cursor: pointer;
  transition: all 0.2s ease;
}

.draft-btn:hover {
  background: #f3f4f6;
  border-color: #d1d5db;
}

.draft-btn svg {
  width: 16px;
  height: 16px;
}

.publish-btn {
  display: flex;
  align-items: center;
  gap: 6px;
  padding: 10px 20px;
  background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
  color: #ffffff;
  border: none;
  border-radius: 8px;
  font-size: 14px;
  font-weight: 600;
  cursor: pointer;
  transition: all 0.3s ease;
  box-shadow: 0 2px 8px rgba(102, 126, 234, 0.2);
}

.publish-btn:hover:not(:disabled) {
  transform: translateY(-2px);
  box-shadow: 0 4px 12px rgba(102, 126, 234, 0.3);
}

.publish-btn:disabled {
  opacity: 0.5;
  cursor: not-allowed;
  transform: none;
}

.publish-btn svg {
  width: 16px;
  height: 16px;
}

.publish-content {
  background: #ffffff;
  margin: 24px;
  border-radius: 12px;
  padding: 32px;
  box-shadow: 0 1px 3px rgba(0, 0, 0, 0.1);
}

.form-section {
  display: flex;
  flex-direction: column;
  gap: 32px;
}

.form-group {
  display: flex;
  flex-direction: column;
  gap: 12px;
}

.form-label {
  font-size: 15px;
  font-weight: 600;
  color: #2b2f36;
}

.required {
  color: #ef4444;
}

.optional {
  font-weight: 400;
  color: #9ca3af;
}

.title-input {
  width: 100%;
  padding: 14px 16px;
  border: 2px solid #e5e7eb;
  border-radius: 8px;
  font-size: 16px;
  font-weight: 500;
  color: #2b2f36;
  transition: all 0.2s ease;
}

.title-input:focus {
  outline: none;
  border-color: #667eea;
  box-shadow: 0 0 0 3px rgba(102, 126, 234, 0.1);
}

.title-input::placeholder {
  color: #9ca3af;
  font-weight: 400;
}

.content-textarea {
  width: 100%;
  padding: 14px 16px;
  border: 2px solid #e5e7eb;
  border-radius: 8px;
  font-size: 15px;
  line-height: 1.6;
  color: #2b2f36;
  resize: vertical;
  min-height: 400px;
  transition: all 0.2s ease;
  font-family: inherit;
}

.content-textarea:focus {
  outline: none;
  border-color: #667eea;
  box-shadow: 0 0 0 3px rgba(102, 126, 234, 0.1);
}

.content-textarea::placeholder {
  color: #9ca3af;
}

.input-tip {
  font-size: 13px;
  color: #9ca3af;
  text-align: right;
}

/* 封面图上传 */
.cover-upload {
  width: 100%;
}

.cover-preview {
  position: relative;
  width: 100%;
  max-width: 600px;
  aspect-ratio: 16 / 9;
  border-radius: 12px;
  overflow: hidden;
}

.cover-preview img {
  width: 100%;
  height: 100%;
  object-fit: cover;
}

.remove-cover-btn {
  position: absolute;
  top: 12px;
  right: 12px;
  width: 32px;
  height: 32px;
  background: rgba(0, 0, 0, 0.6);
  border: none;
  border-radius: 50%;
  color: #ffffff;
  cursor: pointer;
  display: flex;
  align-items: center;
  justify-content: center;
  transition: all 0.2s ease;
}

.remove-cover-btn:hover {
  background: rgba(0, 0, 0, 0.8);
}

.remove-cover-btn svg {
  width: 16px;
  height: 16px;
}

.upload-area {
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
  width: 100%;
  max-width: 600px;
  aspect-ratio: 16 / 9;
  border: 2px dashed #d1d5db;
  border-radius: 12px;
  background: #f9fafb;
  cursor: pointer;
  transition: all 0.2s ease;
}

.upload-area:hover {
  border-color: #667eea;
  background: #f3f4f6;
}

.upload-area svg {
  width: 48px;
  height: 48px;
  color: #9ca3af;
  margin-bottom: 12px;
}

.upload-area p {
  font-size: 15px;
  font-weight: 500;
  color: #4b5563;
  margin: 0 0 4px 0;
}

.upload-area span {
  font-size: 13px;
  color: #9ca3af;
}

/* 文章配图 */
.images-grid {
  display: grid;
  grid-template-columns: repeat(auto-fill, minmax(150px, 1fr));
  gap: 12px;
}

.image-item {
  position: relative;
  aspect-ratio: 1;
  border-radius: 8px;
  overflow: hidden;
  background: #f3f4f6;
}

.image-item img {
  width: 100%;
  height: 100%;
  object-fit: cover;
}

.remove-image-btn {
  position: absolute;
  top: 8px;
  right: 8px;
  width: 24px;
  height: 24px;
  background: rgba(0, 0, 0, 0.6);
  border: none;
  border-radius: 50%;
  color: #ffffff;
  cursor: pointer;
  display: flex;
  align-items: center;
  justify-content: center;
  transition: all 0.2s ease;
}

.remove-image-btn:hover {
  background: rgba(0, 0, 0, 0.8);
}

.remove-image-btn svg {
  width: 14px;
  height: 14px;
}

.upload-image-area {
  aspect-ratio: 1;
  border: 2px dashed #d1d5db;
  border-radius: 8px;
  background: #f9fafb;
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
  cursor: pointer;
  transition: all 0.2s ease;
}

.upload-image-area:hover {
  border-color: #667eea;
  background: #f3f4f6;
}

.upload-image-area svg {
  width: 32px;
  height: 32px;
  color: #9ca3af;
  margin-bottom: 8px;
}

.upload-image-area span {
  font-size: 13px;
  color: #6b7280;
}

/* 标签选择 */
.tags-selector {
  display: flex;
  flex-wrap: wrap;
  gap: 10px;
}

.tag-option {
  padding: 8px 16px;
  background: #f9fafb;
  border: 1px solid #e5e7eb;
  border-radius: 20px;
  font-size: 14px;
  color: #6b7280;
  cursor: pointer;
  transition: all 0.2s ease;
}

.tag-option:hover:not(:disabled) {
  background: #f3f4f6;
  border-color: #d1d5db;
}

.tag-option.active {
  background: #667eea;
  color: #ffffff;
  border-color: #667eea;
}

.tag-option:disabled {
  opacity: 0.5;
  cursor: not-allowed;
}

.selected-tags {
  display: flex;
  align-items: center;
  gap: 12px;
  padding: 12px;
  background: #f0f4ff;
  border-radius: 8px;
}

.selected-label {
  font-size: 13px;
  font-weight: 500;
  color: #667eea;
}

.selected-tags-list {
  display: flex;
  gap: 8px;
  flex-wrap: wrap;
}

.selected-tag {
  display: flex;
  align-items: center;
  gap: 6px;
  padding: 4px 10px;
  background: #667eea;
  color: #ffffff;
  border-radius: 14px;
  font-size: 13px;
}

.remove-tag-btn {
  background: none;
  border: none;
  color: #ffffff;
  font-size: 18px;
  line-height: 1;
  cursor: pointer;
  padding: 0;
  margin-left: 2px;
}

/* 发布确认弹窗 */
.dialog-overlay {
  position: fixed;
  top: 0;
  left: 0;
  right: 0;
  bottom: 0;
  background: rgba(0, 0, 0, 0.5);
  display: flex;
  align-items: center;
  justify-content: center;
  z-index: 9999;
}

.dialog-content {
  background: #ffffff;
  border-radius: 12px;
  padding: 32px;
  max-width: 400px;
  width: 90%;
  box-shadow: 0 20px 25px -5px rgba(0, 0, 0, 0.1);
}

.dialog-title {
  font-size: 20px;
  font-weight: 700;
  color: #2b2f36;
  margin: 0 0 12px 0;
}

.dialog-message {
  font-size: 14px;
  color: #6b7280;
  line-height: 1.6;
  margin: 0 0 24px 0;
}

.dialog-actions {
  display: flex;
  gap: 12px;
  justify-content: flex-end;
}

.cancel-btn,
.confirm-btn {
  padding: 10px 20px;
  border: none;
  border-radius: 8px;
  font-size: 14px;
  font-weight: 600;
  cursor: pointer;
  transition: all 0.2s ease;
}

.cancel-btn {
  background: #f9fafb;
  color: #6b7280;
  border: 1px solid #e5e7eb;
}

.cancel-btn:hover {
  background: #f3f4f6;
}

.confirm-btn {
  background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
  color: #ffffff;
}

.confirm-btn:hover {
  transform: translateY(-1px);
  box-shadow: 0 4px 12px rgba(102, 126, 234, 0.3);
}

/* 全局发布中遮罩 */
.global-loading {
  position: fixed;
  inset: 0;
  background: rgba(255, 255, 255, 0.6);
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
  z-index: 10000;
}

.spinner {
  width: 42px;
  height: 42px;
  border: 3px solid #e5e7eb;
  border-top-color: #667eea;
  border-radius: 50%;
  animation: spin 0.8s linear infinite;
}

.loading-text {
  margin-top: 12px;
  color: #4b5563;
  font-size: 14px;
}

/* 按钮内的微型loading */
.btn-loading {
  display: inline-flex;
  align-items: center;
  gap: 6px;
}

.btn-spinner {
  width: 14px;
  height: 14px;
  border: 2px solid currentColor;
  border-top-color: transparent;
  border-radius: 50%;
  animation: spin 0.8s linear infinite;
}

@keyframes spin {
  to { transform: rotate(360deg); }
}

@media (max-width: 768px) {
  .publish-content {
    margin: 16px;
    padding: 20px;
  }

  .publish-header {
    padding: 16px;
  }

  .publish-title {
    font-size: 18px;
  }

  .header-actions {
    flex-direction: column;
    gap: 8px;
  }

  .images-grid {
    grid-template-columns: repeat(auto-fill, minmax(100px, 1fr));
  }
}
</style>

